﻿using MediatR;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.ChangeTracking;
using Microsoft.Extensions.Logging;
using Sgr.EntityFrameworkCore;
using Sgr.EntityFrameworkCore.Interceptors;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Sgr.UPMS.Infrastructure
{
    /// <summary>
    /// UPMS 只读数据库上下文
    /// </summary>
    public class UpmsReadOnlyDbContext : UpmsDbContext
    {
        private const string ReadOnlyErrorMessage = "This is a read-only context, write operations are not supported";

        public UpmsReadOnlyDbContext(DbContextOptions<UpmsDbContext> options)
            : base(options)
        {
            // 配置为无跟踪查询，提高查询性能
            ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking;

            // 禁用自动检测变更，进一步提高性能
            ChangeTracker.AutoDetectChangesEnabled = false;
        }

        #region 写入操作重写

        /// <summary>
        /// 重写物理删除方法，阻止删除操作
        /// </summary>
        public override void PhysicalDelete<TEntity>(TEntity entity)
        {
            throw new InvalidOperationException(ReadOnlyErrorMessage);
        }

        /// <summary>
        /// 重写保存更改方法，阻止保存操作
        /// </summary>
        public override int SaveChanges(bool acceptAllChangesOnSuccess)
        {
            throw new InvalidOperationException(ReadOnlyErrorMessage);
        }

        /// <summary>
        /// 重写异步保存更改方法，阻止保存操作
        /// </summary>
        public override Task<int> SaveChangesAsync(bool acceptAllChangesOnSuccess,
            CancellationToken cancellationToken = default)
        {
            throw new InvalidOperationException(ReadOnlyErrorMessage);
        }

        /// <summary>
        /// 重写添加实体方法
        /// </summary>
        public override EntityEntry<TEntity> Add<TEntity>(TEntity entity)
        {
            throw new InvalidOperationException(ReadOnlyErrorMessage);
        }

        /// <summary>
        /// 重写更新实体方法
        /// </summary>
        public override EntityEntry<TEntity> Update<TEntity>(TEntity entity)
        {
            throw new InvalidOperationException(ReadOnlyErrorMessage);
        }

        /// <summary>
        /// 重写删除实体方法
        /// </summary>
        public override EntityEntry<TEntity> Remove<TEntity>(TEntity entity)
        {
            throw new InvalidOperationException(ReadOnlyErrorMessage);
        }

        #endregion 写入操作重写
    }
}